package xyz.heyaoshare.config.minio;

import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import xyz.heyaoshare.config.properties.MinioProperties;
import xyz.heyaoshare.config.properties.ProjectProperties;

import java.util.concurrent.TimeUnit;

/**
 * Minio配置类
 * @author YueHe
 * @version 0.0.1
 * @since 2025/6/26 上午10:39
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(ProjectProperties.class)
@ConditionalOnProperty(value = "project.configuration.minio.enable", havingValue = "true")
public class MinioConfig {

    @Bean
    public MinioClient minioClient(MinioProperties minioProperties) {
        log.info("连接Minio中...");
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .httpClient(okHttpClient(minioProperties))
                .build();

        log.info("minio连接完成");
        return minioClient;
    }

    /**
     * 创建一个 OkHttpClient 实例。
     *
     * @return 配置好的 OkHttpClient 实例
     */
    private OkHttpClient okHttpClient(MinioProperties minioProperties) {
        return new OkHttpClient.Builder()
                .connectTimeout(minioProperties.getConnectTimeout(), TimeUnit.SECONDS) // 设置连接超时时间
                .readTimeout(minioProperties.getReadTimeout(), TimeUnit.SECONDS) // 设置读取超时时间
                .writeTimeout(minioProperties.getWriteTimeout(), TimeUnit.SECONDS) // 设置写入超时时间
                .build();
    }

}
